package com.jiyun.xxl.job;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.shaded.com.google.common.base.Splitter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.controller.StatisticsController;
import com.jiyun.dispatch.XxlJobLog;
import com.jiyun.mapper.XxlJobLogMapper;
import com.jiyun.orders.pojo.Orders;
import com.jiyun.service.StatisticsService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zqtao
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class XxlJobTest {

//    @XxlJob("xxlJobTest")
//    public ReturnT<String> xxlJobTest(String date) {
//        log.info("---------xxlJobTest定时任务执行成功--------");
//        return ReturnT.SUCCESS;
//    }

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @Autowired
    private StatisticsService statisticsService;

    @XxlJob("newOrderTaskHandler")
    public void newOrderTaskHandler() {
        //执行订单任务
        log.info("新订单调度任务：{}", XxlJobHelper.getJobId());

        //记录定时任务相关的日志信息
        //封装日志对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        long startTime = System.currentTimeMillis();
        try {
            String param = XxlJobHelper.getJobParam();
            // 解析参数（示例）
            Map<String, String> paramsMap = Splitter.on('&')
                    .withKeyValueSeparator('=')
                    .split(param);

            int pageNum = Integer.parseInt(paramsMap.get("pageNum"));
            int pageSize = Integer.parseInt(paramsMap.get("pageSize"));
            //执行任务
            statisticsService.getData(pageNum, pageSize);

            xxlJobLog.setStatus(1);//成功
        } catch (Exception e) {
            xxlJobLog.setStatus(0);//失败
            xxlJobLog.setError(ExceptionUtil.getAllExceptionMsg(e));
            log.error("定时任务执行失败，任务id为：{}", XxlJobHelper.getJobId());
            e.printStackTrace();
        } finally {
            //耗时
            int times = (int) (System.currentTimeMillis() - startTime);
            xxlJobLog.setTimes(times);
            xxlJobLogMapper.insert(xxlJobLog);
        }
    }

}
